// map.js
import qqmapsdk from '../../../utils/qqmap'
Page({
  onLoad({
    id
  }) {
    this.getRepairDetail(id)
    this.getPolyline()
  },
  async getRepairDetail(id) {
    if (!id) return wx.utils.toast('参数有误')
    const {
      code,
      data: repairDetail
    } = await wx.http.get('/repair/' + id)
    if (code !== 10000) return wx.utils.toast()
    this.setData({
      repairDetail
    })
  },
  getPolyline() {
    //调用距离计算接口
    qqmapsdk.direction({
      mode: 'bicycling', //可选值：'driving'（驾车）、'walking'（步行）、'bicycling'（骑行），不填默认：'driving',可不填
      //from参数不填默认当前地址
      from: '40.22077,116.23128',
      to: '40.225857999999995,116.23246699999999',
      success: (res) => {
        console.log(res);
        var ret = res;
        var coors = ret.result.routes[0].polyline,
          pl = [];
        //坐标解压（返回的点串坐标，通过前向差分进行压缩）
        var kr = 1000000;
        for (var i = 2; i < coors.length; i++) {
          coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
        }
        //将解压后的坐标放入点串数组pl中
        for (var i = 0; i < coors.length; i += 2) {
          pl.push({
            latitude: coors[i],
            longitude: coors[i + 1]
          })
        }
        console.log(pl)
        //设置polyline属性，将路线显示出来,将解压坐标第一个数据作为起点
        this.setData({
          latitude: pl[0].latitude,
          longitude: pl[0].longitude,
          polyline: [{
            points: pl,
            color: '#00c',
            width: 4
          }]
        })
      },
      fail: function (error) {
        console.error(error);
      },
      complete: function (res) {
        console.log(res);
      }
    });
  },
  editRepair(e) {
    wx.navigateTo({
      url: '/repair_pkg/pages/form/index?id=' + e.mark.id,
    })
  },
  // 取消报修
  async cancelRepair(e) {
    // 调用接口
    const {
      code
    } = await wx.http.put('/cancel/repaire/' + e.mark.id)
    if (code !== 10000) return wx.utils.toast()
    // 取消成功
    wx.navigateTo({
      url: '/repair_pkg/pages/list/index'
    })
  },
  data: {
    latitude: 40.060539,
    longitude: 116.343847,
    markers: [{
        id: 1,
        latitude: 40.22077,
        longitude: 116.23128,
        width: 24,
        height: 30,
      },
      {
        id: 2,
        latitude: 40.225857999999995,
        longitude: 116.23246699999999,
        iconPath: '/static/images/marker.png',
        width: 40,
        height: 40,
      },
    ],
  },
})